<?php
class ControllerReportV2Customer extends Controller {
    private $_sortCol = array('date', 'user', 'registerNow', 'orderedNow', 'reOrderedNow', 'orderedNowRate', 'reOrderedNowRate');
    private $_sortSeq = array('asc', 'desc');
    private $_defaultSortCol = 'date';
    private $_defaultSortSeq = 'desc';
    private $_reportStart = '201707';

    public function index() {
        $this->document->addScript('view/javascript/echarts/common.min.js');
        $this->document->addScript('view/javascript/echarts/theme/infographic.js');
        $this->document->addScript('view/javascript/echarts/theme/shine.js');
        $this->load->model('reportV2/customer');
        $data = $this->_initData();
        $data = $this->_initFilter($data);
        $data = $this->_initSort($data);

        $data['filterUserList'] = $this->model_reportV2_customer->getUserInReport();
        $data['reportList'] = $this->_initReportList($this->model_reportV2_customer->getList($data['filter']), $data['sort']);
        $this->response->setOutput($this->load->view('reportV2/customer.tpl', $data));
    }

    protected function _initData($data=array()) {
        $data['token'] = $this->session->data['token'];
        $data['breadcrumbs'] = array(
            array(
                'text' => '首页',
                'href' => $this->url->link('common/dashboard', 'token='.$data['token'], 'SSL'),
            ),
            array(
                'text' => '业务员业绩报表',
                'href' => $this->url->link('reportV2/customer', 'token='.$data['token'], 'SSL'),
            ),
        );
        
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        return $data;
    }

    protected function _initFilter($data=array()) {
        $c = 1;
        $data['filterDateList']['0'] = '所有时间';
        while ($c) {
            $year = date('Y', strtotime('-'.$c.' month'));
            $month = date('m', strtotime('-'.$c.' month'));
            $data['filterDateList'][$year.$month] = $year.'年'.$month.'月';
            $c++;
            if ($year.$month == $this->_reportStart) {
                $c = 0;
                break;
            }
        }
        $data['filter'] = array(
            'date' => trim($this->request->get['filter_date']),
            'user' => intval($this->request->get['filter_user']),
        );
        if (!array_key_exists($data['filter']['date'], $data['filterDateList'])) {
            $data['filter']['date'] = date('Ym', strtotime('-1 month'));
        }
        return $data;
    }

    protected function _initSort($data=array()) {
        $data['sort'] = array(
            'col' => trim($this->request->get['sort_col']),
            'seq' => trim($this->request->get['sort_seq']),
        );
        if (!in_array($data['sort']['col'], $this->_sortCol)) {
            $data['sort']['col'] = $this->_defaultSortCol;
        }
        if (!in_array($data['sort']['seq'], $this->_sortSeq)) {
            $data['sort']['seq'] = $this->_defaultSortSeq;
        }
        return $data;
    }

    public function _initReportList($list, $sort) {
        $shopTypeList = getShopTypes();
        $reportList = $tempList = array();
        $unique = '';
        $mySort = array();
        foreach ($list as $info) {
            $newUnique = $info['report_year'].$info['report_month'].'_'.$info['user_id'];
            if ($unique == $newUnique) {
                $tempList[$newUnique]['registerNow'] += $info['c_register_now'];
                $tempList[$newUnique]['orderedNow'] += $info['c_ordered_now'];
                $tempList[$newUnique]['reOrderedNow'] += $info['c_reordered_now'];
                $tempList[$newUnique]['registerBefore'] += $info['c_register_before'];
                $tempList[$newUnique]['orderedTotal'] += $info['c_ordered_total'];
                $tempList[$newUnique]['registerShopTypes'][$shopTypeList[$info['customer_shop_type']]] = $info['c_register_now']+$info['c_register_before'];
                $tempList[$newUnique]['orderedShopTypes'][$shopTypeList[$info['customer_shop_type']]] = $info['c_ordered_total'];
                if ('Rate' != substr($sort['col'], -4)) {
                    $mySort[$newUnique] = $tempList[$newUnique][$sort['col']];
                }
            }else{
                /* 计算百分比 */
                if ('' != $unique) {
                    $tempList[$unique]['orderedNowRate'] = intval(round($tempList[$unique]['orderedNow']*100/($tempList[$unique]['reOrderedNow']+$tempList[$unique]['registerBefore']), 0));
                    //当月新转化客户数/ (当月复购客户数+当月之前注册数)
                    $tempList[$unique]['reOrderedNowRate'] = intval(round($tempList[$unique]['orderedNow']*100/$tempList[$unique]['orderedTotal']));
                    $tempList[$unique]['lostRate'] = intval(100-$tempList[$unique]['reOrderedNowRate']);
                    if ('Rate' == substr($sort['col'], -4)) {
                        $mySort[$unique] = $tempList[$unique][$sort['col']];
                    }
                }
                /* 初始化新数据 */
                $tempList[$newUnique]['date'] = $info['report_year'].'年'.$info['report_month'].'月';
                $tempList[$newUnique]['user'] = $info['fullname'].'（'.$info['username'].'）';
                $tempList[$newUnique]['registerNow'] = 0;
                $tempList[$newUnique]['registerBefore'] = 0;
                $tempList[$newUnique]['orderedNow'] = 0;
                $tempList[$newUnique]['orderedTotal'] = 0;
                $tempList[$newUnique]['reOrderedNow'] = 0;
                $tempList[$newUnique]['orderedNowRate'] = 0;
                $tempList[$newUnique]['reOrderedNowRate'] = 0;
                $tempList[$newUnique]['lostRate'] = 0;
                $tempList[$newUnique]['registerShopTypes'][$shopTypeList[$info['customer_shop_type']]] = $info['c_register_now']+$info['c_register_before'];
                $tempList[$newUnique]['orderedShopTypes'][$shopTypeList[$info['customer_shop_type']]] = $info['c_ordered_total'];
                $unique = $newUnique;
            }
        }
        /* debug: 循环结束后，计算最后一个月数据的百分比 */
        if ('' != $unique) {
            $tempList[$unique]['orderedNowRate'] = intval(round($tempList[$unique]['orderedNow']*100/($tempList[$unique]['reOrderedNow']+$tempList[$unique]['registerBefore']), 0));
            $tempList[$unique]['reOrderedNowRate'] = intval(round($tempList[$unique]['orderedNow']*100/$tempList[$unique]['orderedTotal']));
            $tempList[$unique]['lostRate'] = intval(100-$tempList[$unique]['reOrderedNowRate']);
            if ('Rate' == substr($sort['col'], -4)) {
                $mySort[$unique] = $tempList[$unique][$sort['col']];
            }
        }
        /* 排序 */
        arsort($mySort);
        if ('asc' == $sort['seq']) {
            asort($mySort);
        }
        foreach ($mySort as $k=>$v) {
            $reportList[] = $tempList[$k];
        }
        /* 排序 */
        // var_dump($reportList);
        return $reportList;
    }
}
